package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constants.RedisConstants;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.constants.SystemConstants;
import com.hmdp.utils.UserHolder;
import io.netty.util.internal.ResourcesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.*;
import static com.hmdp.constants.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * @author zdq
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getCodeByPhone(String phone, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.手机号格式有误
            return Result.fail(SystemConstants.PHONE_REGEN_ERROR);
        }

        // 3.生成验证码，保存于 redis
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 4.发送验证码给用户
        log.debug("验证码为：{}", code);

        // 5.返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();

        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail(SystemConstants.PHONE_REGEN_ERROR);
        }

        // 2.验证验证码是否匹配
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (code == null || !code.equals(loginForm.getCode())) {
            return Result.fail(SystemConstants.CODE_NOT_SUCCESS);
        }

        // 3.身份确认完毕，执行登陆流程
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
            save(user);
        }

        // 将信息存储在 redis 中
        String token = UUID.randomUUID().toString();

        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .ignoreNullValue()
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, map);
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result sign() {
        // 获取 key
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(DateTimeFormatter.ofPattern("yyyy:MM:"));
        Long userId = UserHolder.getUser().getId();

        String key = USER_SIGN_KEY + time + userId;

        // 获取当前是第几天
        int day = now.getDayOfMonth() - 1;

        // redis 写入
        stringRedisTemplate.opsForValue().setBit(key, day, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 获取 key
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(DateTimeFormatter.ofPattern("yyyy:MM:"));
        Long userId = UserHolder.getUser().getId();

        String key = USER_SIGN_KEY + time + userId;

        // 获取当前是第几天
        int day = now.getDayOfMonth();

        // 获取位图
        List<Long> list = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0)
        );
        if (list == null || list.isEmpty()) {
            return Result.ok();
        }

        // 计算连续签到次数
        long num = list.get(0);
        int count = 0;
        while ((num & 1) == 1) {
            count ++;
            num >>>= 1;
        }
        return Result.ok(count);
    }
}
